package com.xing.gulimall.product.service.impl;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xing.common.utils.PageUtils;
import com.xing.common.utils.Query;

import com.xing.gulimall.product.dao.CategoryDao;
import com.xing.gulimall.product.entity.CategoryEntity;
import com.xing.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询所有分类以及子分类，以树形结构封装起来
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查询所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.组装成父子树形结构
        //2.1找到所有一级分类
        List<CategoryEntity> levelMenus = entities.stream().filter(categoryEntity ->
                //当前菜单的的父id=0-->当前菜单为一级菜单
                categoryEntity.getParentCid() == 0
        ).map((menu) -> {
            //找到每一个一级菜单的子菜单
            menu.setChildren(getChildrens(menu, entities));
            return menu;
            //排序菜单
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
            //收集当前所有菜单tolist
        }).collect(Collectors.toList());
        return levelMenus;
    }

    @Override
    public void removeMenuByIds(List<Long> catIdss) {
        //todo 1 .检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(catIdss);
    }


    /**
     * 更新数据并更新关联的中间表数据
     *
     * @param category
     *
     * @CacheEvict 表示一致性中的失效模式（删除缓存）
     * caching 进行 批量操作，精准定位删除，一级和三级分类
     *
     */

    @Caching(
            evict = {
                    @CacheEvict(cacheNames = {"Category"},key="'getLevelCatagories'"),
                    @CacheEvict(cacheNames = {"Category"},key = "'getCatelogJson'")
            }
    )
    //看视频了，不能一直敲代码，不求甚解
    @Override
    public void updateDetail(CategoryEntity category) {

    }




    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);

        return parentPath.toArray(new Long[parentPath.size()]);
    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1.收集当前节点Id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid() != 0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;

    }




    /**
     * 递归查找所有菜单的子菜单
     * 查找当前菜单root的子菜单，从所有菜单all中过滤
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        //依次遍历从所有菜单all中过滤找到当前菜单root的子菜单集合children
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            //当前菜单root的id=过滤对象的父id--->找到当前菜单root的子菜单，
            //即为被过滤的all列表的当前对象CategoryEntity
            return categoryEntity.getParentCid() == root.getCatId();
            //从root找到子菜单列表children可能还有子菜单，
            // 继续查找列表children中的每人一个对象CategoryEntity的子菜单
        }).map(categoryEntity -> {
            //1.找到子菜单
            //递归调用：查找列表children中每一个对象CategoryEntity的子菜单，还是从所有菜单all中过滤的
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
            //2、菜单的排序
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
            //收集当前所有菜单tolist
        }).collect(Collectors.toList());
        return children;
    }


}